'use strict';
const crypto = require('crypto');

// 生成加密token (保持原有格式以兼容前端)
const generateToken = (id) => {
  const timestamp = Date.now();
  const randomStr = crypto.randomBytes(16).toString('hex');
  const data = `${id}:${timestamp}:${randomStr}`;
  const token = crypto.createHmac('sha256', process.env.TOKEN_SECRET || 'your-secret-key')
    .update(data)
    .digest('hex');
  return `${token}.${timestamp}.${randomStr}`;
};

// 获取设备ID
const getDeviceId = async (context) => {
  try {
    const { CLIENTUA, PLATFORM, MODEL, SYSTEM, BRAND } = context;
    if (!CLIENTUA) return null;
    
    const deviceInfo = [
      PLATFORM,
      MODEL,
      SYSTEM,
      BRAND,
      CLIENTUA
    ].filter(Boolean).join(':');
    
    return crypto.createHash('md5').update(deviceInfo).digest('hex');
  } catch (error) {
    console.error('获取设备ID失败:', error);
    return null;
  }
};

exports.main = async (event, context) => {
  console.log('登录请求参数:', event);
  
  const { loginId } = event;
  
  if (!loginId) {
    return {
      success: false,
      message: '登录ID不能为空'
    };
  }

  try {
    // 获取设备ID
    const deviceId = await getDeviceId(context);
    if (!deviceId) {
      return {
        success: false,
        message: '无法获取设备信息'
      };
    }

    const db = uniCloud.database();
    const codeCollection = db.collection('activation_codes');
    
    // 使用loginId作为激活码进行查询
    const { data } = await codeCollection.where({
      code: loginId,
      $or: [
        { status: 'unused' },
        { 
          status: 'used',
          deviceId: deviceId
        }
      ]
    }).get();

    if (data && data.length > 0) {
      const codeInfo = data[0];
      
      // 检查是否已绑定其他设备
      if (codeInfo.status === 'used' && codeInfo.deviceId && codeInfo.deviceId !== deviceId) {
        return {
          success: false,
          message: '该卡密已在其他设备上使用'
        };
      }
      
      // 生成token (使用原有格式)
      const token = generateToken(loginId);
      
      // 更新卡密信息
      const updateData = {
        status: 'used',
        lastLoginTime: Date.now(),
        deviceId: deviceId,
        deviceInfo: {
          platform: context.PLATFORM || '',
          model: context.MODEL || '',
          system: context.SYSTEM || '',
          brand: context.BRAND || '',
          ua: context.CLIENTUA || ''
        },
        lastLoginIP: context.CLIENTIP || '',
        lastLoginUA: context.CLIENTUA || '',
        updateTime: Date.now()
      };
      
      await codeCollection.where({
        code: loginId
      }).update(updateData);

      // 返回与原有格式兼容的响应
      return {
        success: true,
        token,
        message: '登录成功',
        userData: {
          id: loginId,
          lastLoginTime: new Date().toISOString(),
          deviceId: deviceId
        }
      };
    } else {
      // 检查卡密是否被禁用
      const disabledCode = await codeCollection.where({
        code: loginId,
        status: 'disabled'
      }).get();
      
      if (disabledCode.data && disabledCode.data.length > 0) {
        return {
          success: false,
          message: '该卡密已被禁用'
        };
      }
      
      return {
        success: false,
        message: '卡密无效或已被其他设备使用'
      };
    }
  } catch (error) {
    console.error('登录验证失败:', error);
    return {
      success: false,
      message: '登录验证失败，请稍后重试',
      error: error.message
    };
  }
}; 